<?php

namespace Iwester\Http\Controllers\Admin;

use App\Common\SendEmailApi;
use File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Intervention\Image\ImageManager;
use App\Http\Controllers\Controller;
use Iwester\Http\Model\User\User;

class BaseController extends Controller
{

    public $siteConfig;

    public function __construct()
    {
        $this->siteConfig = \Iwester\Http\Model\Config\SiteConfig::getConfig();
        \View::share([
            'siteConfig' => $this->siteConfig
        ]);
    }

    /**
     * 【文件上传】
     * @return array
     */
    public function uploadImg(Request $request)
    {
        try {
            $size = $request->get('size', false);
            //上传文件最大大小,单位M
            $maxSize = 10;
            //支持的上传图片类型
            $allowed_extensions = ["png", "jpg","jpeg", "gif", "ico"];
            //返回信息json
            $data = ['code' => 0, 'msg' => '上传失败', 'path' => ''];

            $file = $request->file('file');
            //检查文件是否上传完成
            if ($file->isValid()) {
                //检测图片类型
                $ext = $file->getClientOriginalExtension();
                if (!in_array(strtolower($ext), $allowed_extensions)) {
                    $data['msg'] = "请上传" . implode(",", $allowed_extensions) . "格式的图片";
                    return $data;
                }
                //检测图片大小
                if ($file->getClientSize() > $maxSize * 1024 * 1024) {
                    $data['msg'] = "图片大小限制" . $maxSize . "M";
                    return $data;
                }
            } else {
                $data['msg'] = $file->getErrorMessage();
                return $data;
            }
            # 存储文件夹
            $dir = '/uploads/';
            $path = $dir . date('Y-m-d');
            File::exists(public_path($dir)) or File::makeDirectory(public_path($dir));
            File::exists(public_path('/') . $path) or File::makeDirectory(public_path('/') . $path);

            # 文件路径
            $newFile = $path . '/' . date('Y-m-d') . "_" . time() . "_" . uniqid() . "." . $file->getClientOriginalExtension();

            $image = new ImageManager();
            $img = $image->make($file);
            if ($size){
                if ($img->width() >= $img->height()) {
                    $height = round(($size / $img->width()) * $img->height(), 3);
                    $img->resize($size, $height);
                } else {
                    $width = round(($size / $img->height()) * $img->width(), 3);
                    $img->resize($width, $size);
                }
            }
            $res = $img->save(public_path($newFile));

            if ($res) {
                $data = [
                    'code' => 200,
                    'msg' => '上传成功',
                    'path' => $newFile
                ];
            } else {
                $data['data'] = $file->getErrorMessage();
            }
            return $data;

        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage(), 'path' => ''];
        }
    }
    
    /**
     * 发送邮箱验证码
     * @param Request $request
     */
    public function sendEmail(Request $request){
        try{
            $toMail = $request->get('email', false);
            $type = $request->get('type', 'register');
            $checkMail = filter_var($toMail, FILTER_VALIDATE_EMAIL);
            if (!$checkMail)  return ['code'=> 201, 'message'=> '请输入正确的邮箱~'];
            $user = User::where('email', $toMail)->first();
            if ($type == 'reset'){
                if (!$user) return ['code'=> 201, 'message'=> '邮箱用户不存在~'];
            }else{
                if ($user) return ['code'=> 201, 'message'=> '邮箱用户已存在~'];
            }
            $token = $request->get('_token', false);
            $tip = $request->get('tip', '');
            $key = $toMail.$token.$type;
            if (\Cache::has($key)) return ['code'=> 201, 'message'=> '验证码已发送请勿重复获取~'];
            $emailVercode = self::emailVercode($key);
            $emailService = new SendEmailApi();
            $content = '您正在'.$tip.'，本次验证码为：'.$emailVercode.'（为了保障您的账号安全性，验证码10分钟内有效，请在规定时间内完成验证）';
            $emailService->send($toMail, $content, '邮箱验证码');
            return ['code'=> 200, 'message'=> '邮件已发送，注意查收~'];
        }catch (\Exception $e){
            return ['code'=> 201, 'message'=> '邮件发送失败，请重试~'];
        }
    }

    /**
     * 生成指定邮箱 - 指定token的验证码
     * @param $mail
     * @param $token
     * @return string
     */
    public static function emailVercode($key){
        $str='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $emailVercode= substr(str_shuffle($str),0,6);
        \Cache::put($key, $emailVercode, 60 *10);
        return $emailVercode;
    }

    public function showpic(Request $request)
    {
        $url = $request->get('url', false);
        if ($url) {
            header('Content-type: image/jpeg');
            echo file_get_contents($url);
        }
    }



}
